/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "spatial_timer.h"

#include "spatial_awareness_common.h"

namespace OHOS {
namespace Msdp {
void SpatialTimer::Start(int interval, NotifyTask &task)
{
    // is started, do not start again
    if (expired_ == false)
        return;

    // start async timer, launch thread and wait in that thread
    expired_ = false;
    std::thread([this, interval, task]() {
        while (!tryToExpire_) {
            // sleep every interval and do the task again and again until times up
            std::this_thread::sleep_for(std::chrono::milliseconds(interval));
            task();
        }

        {
            // timer be stopped, update the condition variable expired and wake main thread
            std::lock_guard<std::mutex> locker(mutex_);
            expired_ = true;
            expiredCond_.notify_one();
        }
    }).detach();
}

void SpatialTimer::StartOnce(int delay, NotifyTask &task)
{
    std::thread([delay, task]() {
        std::this_thread::sleep_for(std::chrono::milliseconds(delay));
        task();
    }).detach();
}

void SpatialTimer::Stop()
{
    // do not stop again
    if (expired_)
        return;

    if (tryToExpire_)
        return;

    // wait until timer
    tryToExpire_ = true; // change this bool value to make timer while loop stop
    {
        std::unique_lock<std::mutex> locker(mutex_);
        expiredCond_.wait(locker, [this] {
            return expired_ == true;
        });

        // reset the timer
        if (expired_ == true)
            tryToExpire_ = false;
    }
}
} // namespace Msdp
} // namespace OHOS